package com.exception;

import com.result.CodeMsg;
import com.result.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.List;

/**
 * @author lvcaihong
 * @dtae 2019/3/4 11:34
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception exception){
        if(exception instanceof GlobalException){
            GlobalException globalException = (GlobalException) exception;
            return Result.error(globalException.getCodeMsg());
        }else if(exception instanceof BindException){
            BindException bindException = (BindException) exception;
//            List<ObjectError> errors = bindException.getAllErrors();
//            ObjectError error = errors.get(0);
//            String msg = error.getDefaultMessage();
            String msg = bindException.getMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }

    }

}
